package com.malty.apimanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.apimanage.dao.UserApiInfoMapper;
import com.malty.apimanage.domain.dto.user.api.UserApiStatistic;
import com.malty.apimanage.service.UserApiInfoService;
import com.malty.common.ErrorCode;
import com.malty.common.domain.entity.UserApiInfo;
import com.malty.common.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 * @description 针对表【user_api_info】的数据库操作Service实现
 * @createDate 2025-09-29 15:52:00
 */
@Service
public class UserApiInfoServiceImpl extends ServiceImpl<UserApiInfoMapper, UserApiInfo>
        implements UserApiInfoService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long getUserApiInvokeCount(Long userId, Long apiId) {
        UserApiInfo apiInfo = getUserApiInfo(userId, apiId);
        return apiInfo.getUsedCalls();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserApiInfo getUserApiInfo(Long userId, Long apiId) {
        UserApiInfo userApiInfo = new UserApiInfo(userId, apiId);
        QueryWrapper<UserApiInfo> wrapper = new QueryWrapper<>(userApiInfo);
        UserApiInfo apiInfo = this.getOne(wrapper);

        if (apiInfo == null) {
            apiInfo = new UserApiInfo(userId, apiId);
            apiInfo.setUsedCalls(0L);
            apiInfo.setAvailableCalls(10L);
            return apiInfo;
        }

        return apiInfo;
    }

    @Override
    public List<UserApiStatistic> getApiStatistics() {
        return this.baseMapper.listApiStatistics();
    }
}




